﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "门户管理-角色")]
public class SysPortalRoleApi : IDynamicApiController
{
    private readonly SysPortalRoleService _service;

    public SysPortalRoleApi(
        SysPortalRoleService service)
    {
        _service = service;
    }

    [QueryParameters]
    public async Task<dynamic> Get(string name)
    {
        var pp = XreqUtil.GetPp();
        var items = await _service.repo.Context.Queryable<SysPortalRole>()
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .OrderBy(u => u.ornum)
            .Select((t) => new {t.id, t.name, t.notes, t.crtim, t.uptim})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }

    public async Task<SysPortalRole> GetOne(string id)
    {
        var role = await _service.repo.Context.Queryable<SysPortalRole>()
            .Mapper<SysPortalRole, SysOrg, SysPortalRoleToOrg>(it =>
                ManyToMany.Config(it.rid, it.oid))
            .Mapper<SysPortalRole, SysPortalMenu, SysPortalRoleToMenu>(it =>
                ManyToMany.Config(it.rid, it.mid))
            .Where(it => it.id == id).FirstAsync();
        return role;
    }

    public async Task Post(SysPortalRole role)
    {
        role.id = YitIdHelper.NextId() + "";
        var romaps = new List<SysPortalRoleToOrg>();
        foreach (var org in role.orgs)
        {
            romaps.Add(new SysPortalRoleToOrg {rid = role.id, oid = org.id});
        }

        var rmmaps = new List<SysPortalRoleToMenu>();
        foreach (var menu in role.menus)
        {
            rmmaps.Add(new SysPortalRoleToMenu {rid = role.id, mid = menu.id});
        }

        await _service.InsertAsync(role, romaps, rmmaps);
        await PostFlush();
    }

    public async Task Put(SysPortalRole role)
    {
        var romaps = new List<SysPortalRoleToOrg>();
        foreach (var org in role.orgs)
        {
            romaps.Add(new SysPortalRoleToOrg {rid = role.id, oid = org.id});
        }

        var rmmaps = new List<SysPortalRoleToMenu>();
        foreach (var menu in role.menus)
        {
            rmmaps.Add(new SysPortalRoleToMenu {rid = role.id, mid = menu.id});
        }
        await _service.UpdateAsync(role, romaps, rmmaps);
        await PostFlush();
    }
    
    public async Task PostFlush()
    {
        await _service.repo.Context.Updateable<SysOrgUser>().SetColumns(it => it.catag == false)
            .Where(it => it.catag == true)
            .ExecuteCommandAsync();
        
        await _service.repo.Context.Updateable<SysCoopUser>().SetColumns(it => it.catag == false)
            .Where(it => it.catag == true)
            .ExecuteCommandAsync();
    }

    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        await _service.DeleteAsync(ids);
    }
}